package com.distribute.proxy;

import com.distribute.ServiceContext;
import com.distribute.config.Config;
import com.distribute.constants.AdminIdentity;
import com.distribute.pojo.user.Tenant;
import com.distribute.pojo.user.User;
import config.DSConfig;
import core.DSApiClient;
import core.api.ApiClient;
import service.DSTenantService;
import service.DSUserService;
import service.api.TenantService;
import service.api.UserService;

public class DolphinSchedulerAdminProxy {

    private static volatile DolphinSchedulerAdminProxy instance;

    // integrate service
    // tenant service
    // user service
    private final UserService userService;

    private final TenantService tenantService;

    private DolphinSchedulerAdminProxy(DSConfig dsConfig) {
        ApiClient apiClient = new DSApiClient(dsConfig);
        userService = new DSUserService(apiClient);
        tenantService = new DSTenantService(apiClient);
    }

    public static DolphinSchedulerAdminProxy getInstance(Config config) {
        if (instance == null) {
            synchronized (DolphinSchedulerAdminProxy.class) {
                if (instance == null) {
                    DSConfig dsConfig = new DSConfig(config.getUrl(),
                            AdminIdentity.ADMIN, AdminIdentity.ADMIN_PWD,
                            config.getTimeout(), config.getRetryTimes());
                    instance = new DolphinSchedulerAdminProxy(dsConfig);
                }
            }
        }
        return instance;
    }


    /**
     * 根据服务名称分配用户账户 并绑定租户
     *
     * @param
     * @return
     */
    public User assignUser(Tenant  tenant) {
        String serviceName = ServiceContext.getInstance().getServiceName();
        User user = userService.getUser(serviceName);
        if (user == null) {
            user = userService.createUser(serviceName, serviceName + 123, tenant.getId(),
                    serviceName + "@qq.com", "default", "18188888888", 1);
        }
        return user;
    }

    public Tenant assignTenant() {
        Tenant serviceTenant = tenantService.getTenant(ServiceContext.getInstance().getServiceName());
        if (serviceTenant == null) {
            serviceTenant = tenantService.createTenant(ServiceContext.getInstance().getServiceName(),
                    1, ServiceContext.getInstance().getServiceName());
        }
        return serviceTenant;
    }


}
